﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
using static System.Threading.Thread;

namespace Project_4
{
    /// <summary>
    /// 4.4 组合任务，设置相互依赖的父子任务
    /// </summary>
    public class Unit_4_04
    {
        /*
         * 任务的延续，开启子任务
         * task.ContinueWith(t=>{});
         *
         */
        public static void Go()
        {
            var firstTask=new Task<int>(()=>TaskMethod("FirstTask",3));
            var secondTask=new Task<int>(()=>TaskMethod("SecondTask",2));

            firstTask.ContinueWith(t => WriteLine($"Second Result：{t.Result}." +
                                                  $" 线程id：{CurrentThread.ManagedThreadId}," +
                                                  $" 是否是线程池的线程:{CurrentThread.IsThreadPoolThread} "),
                TaskContinuationOptions.OnlyOnRanToCompletion);
            firstTask.Start();
            secondTask.Start();
            Sleep(TimeSpan.FromSeconds(4));

            Task continuation= secondTask.ContinueWith(t => WriteLine($"First Result：{t.Result}." +
                                                                     $" 线程id：{CurrentThread.ManagedThreadId}," +
                                                                     $" 是否是线程池的线程:{CurrentThread.IsThreadPoolThread} "),
                TaskContinuationOptions.OnlyOnRanToCompletion |TaskContinuationOptions.ExecuteSynchronously);

            continuation.GetAwaiter().OnCompleted(() => WriteLine($"延续任务执行完成！" +
                                                                  $"线程id：{CurrentThread.ManagedThreadId}" +
                                                                  $" 是否是线程池的线程:{CurrentThread.IsThreadPoolThread} "));
            Sleep(TimeSpan.FromSeconds(2));
            WriteLine();

            firstTask=new Task<int>(() =>
            {
                var innerTask = Task.Factory.StartNew(() => TaskMethod("Second Task", 5),
                    TaskCreationOptions.AttachedToParent);

                innerTask.ContinueWith(t => TaskMethod("Third Task", 2), TaskContinuationOptions.AttachedToParent);
                return TaskMethod("First Task", 2);
            });

            firstTask.Start();

            while (!firstTask.IsCompleted)
            {
                WriteLine(firstTask.Status);
                Sleep(TimeSpan.FromSeconds(0.5));
            }

            WriteLine(firstTask.Status);

            Sleep(TimeSpan.FromSeconds(10));
        }

        static int TaskMethod(string name, int seconds)
        {
            WriteLine($"任务 {name} 运行在 id为：{CurrentThread.ManagedThreadId} 的线程上，" +
                      $" 是否是线程池的线程：{CurrentThread.IsThreadPoolThread} ");
            Sleep(TimeSpan.FromSeconds(seconds));
            return seconds;
        }
    }
}
